package com.example.weatherforecast.whtrcdn.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.weatherforecast.R
import com.example.weatherforecast.whtrcdn.WhtrcdnViewModel
import com.example.weatherforecast.whtrcdn.adapter.WeatherCitySearchResultListAdapter
import com.example.weatherforecast.whtrcdn.constant.WhtrcdnConstant
import com.example.weatherforecast.whtrcdn.entity.WeatherCityInfo
import kotlinx.android.synthetic.main.activity_weather_city_add.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class WeatherCityAddActivity : AppCompatActivity() {

    private var viewModel: WhtrcdnViewModel ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather_city_add)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(
            WhtrcdnViewModel::class.java)

        rv_weather_city_hot.layoutManager = GridLayoutManager(this, 5, GridLayoutManager.VERTICAL, false)
        rv_weather_city_hot.adapter = object : RecyclerView.Adapter<MyViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
                return MyViewHolder(LayoutInflater.from(this@WeatherCityAddActivity).inflate(R.layout.weather_city_search_list_item, parent, false))
            }
            override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
                holder.cityNameLabel.text = WhtrcdnConstant.HOT_CITY_LIST[position]
                holder.cityNameLabel.setOnClickListener{
                    val cityList = viewModel?.getCurrentWeatherCityInfoList() ?: return@setOnClickListener
                    if(viewModel?.checkCurrentWeatherCityDuplicated(cityList, WhtrcdnConstant.HOT_CITY_LIST[position]) == true){
                        Toast.makeText(this@WeatherCityAddActivity, "该城市已添加: " + WhtrcdnConstant.HOT_CITY_LIST[position], Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }

                    if (cityList.size > WhtrcdnConstant.CITY_COUNT_LIMIT){
                        Toast.makeText(this@WeatherCityAddActivity, "城市数量已达到上限，最多${WhtrcdnConstant.CITY_COUNT_LIMIT}个", Toast.LENGTH_SHORT).show()
                    }else {
                        lifecycleScope.launch(Dispatchers.IO) {
                            viewModel?.cityInfoRepository?.queryByCityName(WhtrcdnConstant.HOT_CITY_LIST[position]).also { cityInfo ->
                                if (cityInfo != null){
                                    cityList.add(WeatherCityInfo(cityInfo.cityName, cityInfo.cityId, 0))
                                    viewModel?.updateCurrentWeatherCityInfoList(cityList)

                                    lifecycleScope.launch(Dispatchers.Main) {
                                        Toast.makeText(this@WeatherCityAddActivity, "添加成功: " + WhtrcdnConstant.HOT_CITY_LIST[position], Toast.LENGTH_SHORT).show()
                                    }
                                }else {
                                    lifecycleScope.launch(Dispatchers.Main) {
                                        Toast.makeText(this@WeatherCityAddActivity, "未查询到该城市: " + WhtrcdnConstant.HOT_CITY_LIST[position], Toast.LENGTH_SHORT).show()
                                        }
                                }
                            }
                        }
                    }
                }
            }
            override fun getItemCount(): Int = WhtrcdnConstant.HOT_CITY_LIST.size
        }
        rv_weather_city_search_result.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        val citySearchResultListAdapter = WeatherCitySearchResultListAdapter(this, ArrayList(),
            viewModel!!
        )
        rv_weather_city_search_result.adapter = citySearchResultListAdapter

        et_weather_city_search.addTextChangedListener { etData ->
            val searchCityName = etData.toString().trim()
            if (searchCityName.isNotEmpty()){
                lifecycleScope.launch(Dispatchers.IO) {
                    viewModel?.cityInfoRepository?.queryAllBlur("%$searchCityName%").also {
                        if (it != null) {
                            lifecycleScope.launch(Dispatchers.Main) {
                                citySearchResultListAdapter.updateData(it)
                                citySearchResultListAdapter.notifyDataSetChanged()
                            }
                        }
                    }
                }
            }else {
                lifecycleScope.launch(Dispatchers.Main) {
                    citySearchResultListAdapter.updateData(ArrayList())
                    citySearchResultListAdapter.notifyDataSetChanged()
                }
            }
        }
    }
}

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val cityNameLabel: TextView = itemView.findViewById(R.id.tv_weather_city_name_label)
}
